<?php

namespace App\Http\Middleware;

use App\Helpers\RestUtils;
use App\Models\Factory\UserFactory;
use Closure;
use App\Helpers\RestResponseFactory;


/**
 * token验证中间件
 *
 * Class TokenMiddleware
 * @package App\Http\Middleware
 */
class TokenMiddleware
{
    public function handle($request, Closure $next)
    {

        if (!$request->has('token')) {

            return RestResponseFactory::ok(RestUtils::getStdObj(), 2, 2, RestUtils::getErrorMessage(2));
        }

        $token = $request->input('token');

        $user = UserFactory::getUser($token);

        if (!$user) {

            return RestResponseFactory::ok(RestUtils::getStdObj(), 2, 2, RestUtils::getErrorMessage(2));

        }

        $request->attributes->add(compact('user'));

        return $next($request);

    }

}
